package com.soft.mainsite.module.web.system;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.soft.mainsite.common.annotation.SysLog;
import com.soft.mainsite.common.constant.CmsConst;
import com.soft.mainsite.common.domain.ErrorCode;
import com.soft.mainsite.common.utils.JsonUtil;
import com.soft.mainsite.module.staticstrategy.staticservice.StaticHtmlService;
import com.soft.mainsite.module.web.cms.service.CategoryService;
import com.soft.mainsite.module.web.cms.service.ContentService;
import com.soft.mainsite.module.web.cms.service.SiteService;
import com.soft.mainsite.mybatis.model.TCmsCategory;
import com.soft.mainsite.mybatis.model.TCmsContent;
import com.soft.mainsite.mybatis.model.TCmsSite;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 页面静态化controller
 *
 * @author liupengtao
 * @date 2019/04/29
 */
@Slf4j
@Controller
@RequestMapping("/system/toStaticHtml")
public class HtmlStaticController {

    @Autowired
    private SiteService siteService;

    @Autowired
    private StaticHtmlService staticHtmlService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ContentService contentService;

    @Value("${system.site.static.path}")
    String staticPath;

    /**
     * 移动端静态化
     */
    private static final int STATIC_TYPE_MOBILE = 1;
    /**
     * PC端静态化
     */
    private static final int STATIC_TYPE_PC = 2;

    @RequestMapping
    public String index() {
        return "system/site_static";
    }


    /**
     * 静态化转发页面
     *
     * @param siteId 站点id
     * @return 是否成功的提示
     */
    @RequestMapping("/siteForwardStatic/{siteId}")
    @ResponseBody
    public String siteForwardStatic(@PathVariable("siteId") Integer siteId) {
        try {
            return staticHtmlService.forward(siteId, CmsConst.TPL_TYPE_MOBILE);
        } catch (Exception e) {
            log.error("静态化转发页面失败,站点id:{}", siteId, e);
        }
        return JsonUtil.toSuccess("页面静态化成功");
    }

    /**
     * 静态化站点首页
     *
     * @param siteId 站点id
     * @return 是否成功的提示
     */
    @RequestMapping("/siteIndexStatic/{siteId}")
    @ResponseBody
    public String siteIndexStatic(@PathVariable("siteId") Integer siteId) {
        try {
            return staticHtmlService.index(siteId, CmsConst.TPL_TYPE_MOBILE);
        } catch (Exception e) {
            log.error("静态化站点首页失败,站点id:{}", siteId, e);
        }
        return JsonUtil.toError("静态化站点首页失败");
    }

    /**
     * 静态化栏目
     *
     * @param siteId 站点id
     * @param categoryIds 栏目id
     * @return 是否成功的提示
     */
    @RequestMapping("/siteCategoryStatic")
    @ResponseBody
    public String siteCategoryStatic(@RequestParam("siteId") Integer siteId, @RequestParam("categoryIds") String categoryIds) {

        if (StrUtil.isBlank(categoryIds)) {
            return JsonUtil.toError(ErrorCode.E_100120.getDesc());
        }

        String[] categoryIdArray = categoryIds.split(",");
        for (String id : categoryIdArray) {
            try {
                this.staticHtmlService.category(siteId, Long.parseLong(id), CmsConst.TPL_TYPE_MOBILE);
                this.generateContent(siteId, Convert.toLong(id), CmsConst.TPL_TYPE_MOBILE);
            } catch (Exception e) {
                log.error("静态化栏目失败,站点id:{}", siteId, e);
            }

        }

        return JsonUtil.toSuccess("页面静态化成功");

    }


    /**
     * 静态化站点
     *
     * @param siteId 站点id
     * @return 是否成功的提示
     */
    @RequestMapping("/siteStatic/{siteId}")
    @ResponseBody
    public String siteStatic(@PathVariable("siteId") Integer siteId) {
        try {
            this.staticHtmlService.index(siteId, CmsConst.TPL_TYPE_MOBILE);
            this.generateCategory(siteId,CmsConst.TPL_TYPE_MOBILE);
        } catch (Exception e) {
            log.error("静态化站点失败,站点id:{}", siteId, e);
        }

        return JsonUtil.toSuccess("静态化成功.");
    }


    /**
     * 站点批量静态化
     *
     * @param siteIds 站点Id
     * @param staticType 静态化类型
     * @return 是否成功的提示
     */
    @SysLog("站点批量静态化")
    @RequestMapping("/bathStatic")
    @ResponseBody
    public String bathStatic(@RequestBody String[] siteIds, @RequestParam("staticType") Integer staticType) {


        if (ArrayUtil.isEmpty(siteIds)) {
            return JsonUtil.toError("请至少选择一个站点");
        }

        // staticType 0:PC端 + 移动端, 1: 移动端, 2: PC端
        switch (staticType){
            case STATIC_TYPE_MOBILE:
                staticHtml(siteIds,CmsConst.TPL_TYPE_MOBILE);
                break;
            case STATIC_TYPE_PC:
                staticHtml(siteIds,CmsConst.TPL_TYPE_PC);
                break;
            default:
                staticHtml(siteIds,CmsConst.TPL_TYPE_MOBILE);
                staticHtml(siteIds,CmsConst.TPL_TYPE_PC);
                break;
        }
        return JsonUtil.toSuccess("静态页面正在生成....");
    }
    private void staticHtml(String[] siteIds,String staticType) {
        Arrays.asList(siteIds).forEach(id -> {
            boolean staticFlag = true;

            try {
                generateCategory(Convert.toInt(id),staticType);
                staticHtmlService.forward(Convert.toInt(id), staticType);
                staticHtmlService.index(Convert.toInt(id), staticType);
            } catch (Exception e) {
                staticFlag = false;
            }

            siteService.updateStaticStatus(Convert.toInt(id), staticFlag);

        });
    }

    /**
     * 公共栏目初始化
     *
     * @return 是否成功的提示
     */
    @RequestMapping("/commonListStatic")
    @ResponseBody
    public String commonListStatic() {

        return JsonUtil.toError("删除静态html失败");
    }


    /**
     * 删除站点静态化文件
     *
     * @param siteId 站点id
     * @return 是否成功的提示
     */
    @RequestMapping("/{siteId}/clear")
    @ResponseBody
    public String clear(@PathVariable("siteId") Integer siteId) {
        TCmsSite site = siteService.findById(siteId);
        File file = new File(staticPath + File.separator + "mainsite" + File.separator + site.getSiteKey() + File.separator + "mobile");
        try {
            FileUtils.deleteDirectory(file);
        } catch (IOException e) {
            return JsonUtil.toError("删除静态html失败！\n" + e.getMessage());
        }
        return JsonUtil.toSuccess("删除静态html成功");
    }


    /**
     * 静态化站点所有栏目
     *
     * @param siteId 站点id
     */
    private void generateCategory(Integer siteId,String staticType) throws Exception {
        List<TCmsCategory> categoryList = categoryService.findInitCategoryList(siteId, CmsConst.IS_PUB);

        this.staticHtmlService.initSinglePage(siteId, staticType);

        for (TCmsCategory category : categoryList) {
            //先内容后栏目 自下而上
            this.generateContent(siteId, category.getCategoryId(), staticType);
            this.staticHtmlService.category(siteId, category.getCategoryId(), staticType);
        }
    }

    /**
     * 静态化内容页
     *
     * @param siteId 站点id
     * @param categoryId 栏目id
     * @param tplType 模板类型
     */
    private void generateContent(Integer siteId, Long categoryId, String tplType) throws Exception {
        TCmsCategory category = categoryService.findById(categoryId);
        List<TCmsContent> contentList = contentService.findBySiteIdAndCategoryId(siteId, categoryId);
        boolean isPub = false;
        if (CmsConst.MAIN_SITE_ID.equals(siteId) && category.getIsCommon()) {
            isPub = true;
        }
        for (TCmsContent content : contentList) {
            staticHtmlService.content(siteId, categoryId, content.getContentId(), tplType, isPub);
        }
    }


}
